package cn.bearspark.like.provider.service.impl;

import cn.bearspark.common.enumeration.LikedEnum;
import cn.bearspark.like.provider.dao.buffer.CommentLikeZSetBuffer;
import cn.bearspark.like.provider.dao.mapper.CommentLikeMapper;
import cn.bearspark.like.provider.service.CommentLikeService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author f
 */
@Service
public class CommentLikeServiceImpl implements CommentLikeService {

    private final CommentLikeMapper commentLikeMapper;

    private final CommentLikeZSetBuffer commentLikeZSetBuffer;

    public CommentLikeServiceImpl(CommentLikeMapper commentLikeMapper,
                                  CommentLikeZSetBuffer commentLikeZSetBuffer) {
        this.commentLikeMapper = commentLikeMapper;
        this.commentLikeZSetBuffer = commentLikeZSetBuffer;
    }

    @Override
    public int likeComment(long userId, long commentId, int liked) {
        boolean isLiked = commentLikeZSetBuffer.filter(List.of(commentId), userId).contains(commentId);

        if (liked == LikedEnum.LIKED.getCode()) {
            // 如果用户点赞过该评论，则不能再次点赞
            if (isLiked) {
                return 0;
            }

            // 如果 liked 是点赞，则保存记录
            return commentLikeMapper.insert(userId, commentId);
        } else {
            // 如果用户没有点赞过该评论，则不能取消点赞
            if (!isLiked) {
                return 0;
            }

            // 如果 liked 是未点赞，则删除记录
            int row = commentLikeMapper.delete(userId, commentId);

            // 清理用户的点赞评论缓存
            commentLikeZSetBuffer.clean(commentId, userId);

            return row;
        }
    }

    @Override
    public Set<Long> getLikedCommentIdSet(List<Long> commentIdList, long userId) {
        return commentLikeZSetBuffer.filter(commentIdList, userId);
    }
}
